package com.juku2024.juku.adapter

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.juku2024.juku.R
import com.juku2024.juku.model.CategorySearchTagModel
import com.juku2024.juku.tools.WrapLinearLayoutManager
import com.juku2024.juku.widget.CategorySearchTagView
import java.util.ArrayList

class CategorySearchTagListAdapter(category: MutableList<ArrayList<CategorySearchTagModel>>, private val callback: CategorySearchTagView.OnCategoryGTagSelectedCallback?):
    BaseQuickAdapter<ArrayList<CategorySearchTagModel>, BaseViewHolder>(R.layout.item_category_search_key, category) {

    init {
//        category.forEach { it.firstOrNull()?.isSelected = true }
    }

    override fun convert(holder: BaseViewHolder, item: ArrayList<CategorySearchTagModel>) {
        val searchTagRecycler = holder.getView<RecyclerView>(R.id.searchTagRecycler)
        searchTagRecycler.setHasFixedSize(true)
        searchTagRecycler.layoutManager = WrapLinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        val adapter = CategorySearchTagItemAdapter(item)
        adapter.setOnItemClickListener { _, _, position ->
            val index = adapter.data.indexOfFirst { it.isSelected }
            if (index != -1 && index != position) {
                adapter.data[index].isSelected = false
                adapter.notifyItemChanged(index)
                val currentItem = adapter.data[position]
                currentItem.isSelected = true
                adapter.notifyItemChanged(position)
                callback?.onSearchKeySelected(position, currentItem)
            }
        }
        searchTagRecycler.adapter = adapter
    }
}